// FcpuDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Fcpu.h"
#include "FcpuDlg.h"

#include "umfh.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFcpuDlg dialog

CFcpuDlg::CFcpuDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CFcpuDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CFcpuDlg)
	m_strMsg = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	icdev=-1;
	pstrMsg="";
	cardtype=-1;
}

void CFcpuDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFcpuDlg)
	DDX_Control(pDX, IDC_EDT_COMMAND, m_edtCmd);
	DDX_Control(pDX, IDC_EDT_MSG, m_editMsg);
	DDX_Text(pDX, IDC_EDT_MSG, m_strMsg);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CFcpuDlg, CDialog)
	//{{AFX_MSG_MAP(CFcpuDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_TEST, OnBtnTest)
	ON_BN_CLICKED(ID_BTN_CLEAR, OnBtnClear)
	ON_BN_CLICKED(ID_BTN_RESET, OnBtnReset)
	ON_BN_CLICKED(IDC_BTN_SENDCMD, OnBtnSendcmd)
	ON_COMMAND(ID_MENU_OPEN, OnMenuOpen)
	ON_COMMAND(ID_MENU_CPU, OnMenuCpu)
	ON_COMMAND(ID_MENU_FCPU, OnMenuFcpu)
	ON_COMMAND(ID_MENU_CLOSE, OnMenuClose)
	ON_COMMAND(ID_MENU_SAM1, OnMenuSam1)
	ON_COMMAND(ID_MENU_SAM2, OnMenuSam2)
	ON_COMMAND(ID_MENU_SAM3, OnMenuSam3)
	ON_COMMAND(ID_MENU_TypeB, OnMENUTypeB)
	ON_BN_CLICKED(IDC_BTN_ID, OnBtnCPUId)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFcpuDlg message handlers

BOOL CFcpuDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_edtCmd.SetWindowText("8088020180BF0C0AA99EA0E37D6980EB2DF721C7ACBC5A974F16DE2987D49D51F5B97E8B8A789DF0DDF17433842F39AEF47B02D19F0E364E26A7D7FB9B9ACD8D327F4311460D627627B6C59AF46BE6F9680D96482C2C326A1DCCCB8D511BE017850E296C490391E3794EC18ED12E2E407D0089A30766912E0C3AEA6EE7D43F7C8A57E2F47D");
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CFcpuDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CFcpuDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CFcpuDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}
 
void CFcpuDlg::OnBtnTest() //Card reset
{
	// TODO: Add your control notification handler code here

	int st;
	switch(cardtype)
	{
	case FCPU:
		{
			
			//find card
			CString strCard;
			unsigned long snCard;
			st =fw_config_card((HANDLE)icdev,'A');
			st=fw_card(icdev,0,&snCard);
			if(st)
			{
				ShowMsgString(_T("fw_card Error!"));
				return;
			}
			else{
				ShowMsgString(_T("fw_card OK!"));
				strCard.Format("Card serial number: %u",snCard);
				ShowMsgString(strCard);
			}
			
			//Reset 
			unsigned char rlen;
			unsigned char rData[256]={0};
			unsigned char showData[256]={0};
			st=fw_pro_reset(
				icdev,
				&rlen,
				rData);
			if(st)
			{
				ShowMsgString(_T("fw_pro_reset Error!"));
				return;
			}
			
			ShowMsgString(_T("fw_pro_reset OK!"));
			CString strResetInfo("Information after reset: ");
			
			hex_a(showData,rData,rlen*2);
			
			strResetInfo+=showData;
			ShowMsgString(strResetInfo);
		}
		break;
	case CPU:
	case SAM1:
	case SAM2:
	case SAM3:
		{
			unsigned char relen;
			unsigned char rebuffer[255];
			unsigned char rtempBuffer[255];
			
			memset(rebuffer,0,255);
			memset(rtempBuffer,0,255);
			if(!fw_cpureset((HANDLE)icdev,&relen,rebuffer))
			{
				ShowMsgString("Reset card OK!");
				hex_a(rtempBuffer,rebuffer,2*relen);
				ShowMsgString(rtempBuffer);
				return;
			}
			
			ShowMsgString("Reset card error");
		}
	default:
		ShowMsgString(_T("Have not Selected a card,Select first please!"));
		break;
	}


}

void CFcpuDlg::ShowMsgString(CString strMsg)
{
	pstrMsg="\r\n"+pstrMsg;
	pstrMsg=strMsg+pstrMsg;

	m_strMsg=pstrMsg;

	UpdateData(FALSE);

}

void CFcpuDlg::ShowMsgchar(unsigned char *showbuf)
{
	CString strtmp(showbuf);

	pstrMsg="\r\n"+pstrMsg;
	pstrMsg=strtmp+pstrMsg;

	m_strMsg=pstrMsg;

	UpdateData(FALSE);

}

void CFcpuDlg::OnBtnClear() 
{
	// TODO: Add your control notification handler code here

	m_strMsg=pstrMsg="";
	UpdateData(FALSE);
}

void CFcpuDlg::OnBtnReset() 
{
	// TODO: Add your control notification handler code here
	//RF reset
	int st;
	st=fw_reset((HANDLE)icdev,2);
	if(st)
	{
		ShowMsgString(_T("fw_reset Error!"));
		return;
	}
	ShowMsgString(_T("fw_reset OK!"));
}



void CFcpuDlg::OnBtnSendcmd() 
{
	// TODO: Add your control notification handler code here
	int st;
	//Sent command
	switch(cardtype)
	{
	case FCPU:                    //Contactless-CPU sent command
		{
			unsigned char srvBuffer[256];
			unsigned char sendlen=75;
			unsigned char revBuffer[256];
			unsigned char revstr[512]={0};
			unsigned char ftt=9;
			unsigned char fFG=7;//
			unsigned char revlen;
			
			CString strCommand("");
			m_edtCmd.GetWindowText(strCommand);
			
			int strlen=strCommand.GetLength();
			unsigned char cmdbuf[500];
			memcpy(cmdbuf,strCommand.GetBuffer(strlen),strlen);
			strCommand.ReleaseBuffer();
			
			a_hex((unsigned char*)srvBuffer,(unsigned char*)cmdbuf,strlen/2);
			sendlen=strlen/2;
			
			
			st=fw_pro_commandlink
				(
				icdev,//reader handle value
				sendlen,//the length of sent information
				srvBuffer,//the information to sent
				&revlen,//length of returned information
				revBuffer,//the information returned
				ftt,//relay time: Unit: 10ms
				fFG//split length,should small than 64
				);
			if(st)
			{
				ShowMsgString(_T("fw_pro_commandlink Error!"));
				return;
			}
			
			ShowMsgString(_T("fw_pro_commandlink OK!"));
			CString strResetInfo("Information after execute command: ");
			
			hex_a(revstr,revBuffer,revlen*2);
			
			strResetInfo+=revstr;
			ShowMsgString(strResetInfo);
		}
		break;
	case CPU:
	case SAM1:
	case SAM2:
	case SAM3:
		{
			unsigned char sentBuffer[255];
			unsigned char realsentBuf[255];
			
			unsigned char relen;
			unsigned char reBuffer[255];
			unsigned char rtempBuffer[255];
			memset(sentBuffer,0,255);
			memset(realsentBuf,0,255);
			memset(reBuffer,0,255);
			memset(rtempBuffer,0,255);
			
			CString m_commandInfo;
			char * commandBuf;
			for(int i=0;i<5;i++)
			{
				
				m_commandInfo.ReleaseBuffer();
				
				switch(i)
				{
				case 0:
					m_commandInfo=_T("00A40000022F02");
					commandBuf="00A40000022F02";
					break;
				case 1:
					m_commandInfo=_T("00A4020002ef02");
					commandBuf="00A4020002ef02";
					break;
				case 2:
					m_commandInfo=_T("002000000412345678");
					commandBuf="002000000412345678";
					break;
				case 3:
					m_commandInfo=_T("00d600003c112233445566778811223344556677881122334455667788112233445566778811223344556677881122334455667788112233445566778811223344");
					commandBuf="00d600003c112233445566778811223344556677881122334455667788112233445566778811223344556677881122334455667788112233445566778811223344";
					break;
				case 4:
					m_commandInfo=_T("00b000003c");
					commandBuf="00b000003c";
					break;
				default:
					break;
				}
				
				int sentInfolen=strlen(m_commandInfo)/2;
				
				for(int j=0;j<2*sentInfolen;j++)
				{
					sentBuffer[j]=m_commandInfo.GetAt(j);
				}
				
				memset(realsentBuf,0,255);
				
				a_hex(realsentBuf,sentBuffer,sentInfolen);
				
				if(!fw_cpuapdu((HANDLE)icdev,(unsigned char)sentInfolen,
					realsentBuf,&relen,reBuffer))
				{
					ShowMsgString("Send :");
					ShowMsgchar((unsigned char*)commandBuf);
					
					
					hex_a(rtempBuffer,reBuffer,2*relen);
					ShowMsgString("Receive:");
					ShowMsgchar((unsigned char*)rtempBuffer);
					continue;
				}
				
				ShowMsgString("Send command error!");
			}
		}
		break;
	default:
		ShowMsgString(_T("Have not Selected a card,Select first please!"));
		break;
	}
}

void CFcpuDlg::OnMenuOpen() 
{
	// TODO: Add your command handler code here
	int st;
	if(icdev<0)
	{
		icdev=fw_init(100,115200);//first parameter: 100 means USB, otherwise set serial port
		
		if(icdev<=0)
		{
			AfxMessageBox(_T("Reader open failed!"));
			return;
		}
		
		st=fw_beep(icdev,10);
		if(st)
		{
			AfxMessageBox(_T("Reader open failed!"));
			return;
		}
		
		ShowMsgString(_T("Reader open success"));
	}

}

void CFcpuDlg::OnMenuCpu() 
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}
	if(fw_setcpu((HANDLE)icdev,CPU))
	{
		ShowMsgString("set CPU error!");
		return;
	}
	ShowMsgString("set CPU OK!");
	cardtype=CPU;
}

void CFcpuDlg::OnMenuFcpu() 
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}
	cardtype=FCPU;
}

void CFcpuDlg::OnMENUTypeB()    //TypeB CPU
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}
	cardtype=TypeB;
}

void CFcpuDlg::OnMenuClose() 
{
	// TODO: Add your command handler code here
	int st;
	st=fw_exit(icdev);
	if(st)
	{
		ShowMsgString("Unlink device Error!");
		return;
	}

	ShowMsgString("Unlink device OK!");
	icdev=-1;

}

void CFcpuDlg::OnMenuSam1() 
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}

	if(fw_setcpu((HANDLE)icdev,SAM1))
	{
		ShowMsgString("set SAM1  error!");
		return;
	}
	ShowMsgString("set SAM1 OK!");

	cardtype=SAM1;
}

void CFcpuDlg::OnMenuSam2() 
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}

	if(fw_setcpu((HANDLE)icdev,SAM2))
	{
		ShowMsgString("set SAM2  error!");
		return;
	}
	ShowMsgString("set SAM2 OK!");

	cardtype=SAM2;
}

void CFcpuDlg::OnMenuSam3() 
{
	// TODO: Add your command handler code here
	if(icdev<0)
	{
		ShowMsgString(_T("Device is not Open!"));
		return;
	}

	if(fw_setcpu((HANDLE)icdev,SAM3))
	{
		ShowMsgString("set SAM3  error!");
		return;
	}
	ShowMsgString("set SAM3 OK!");

	cardtype=SAM3;
}



void CFcpuDlg::OnBtnCPUId() 
{
	// TODO: Add your control notification handler code here
	unsigned char ATQB[15] ;
			unsigned char UIDinfo[11] ;
			unsigned char len ;
			unsigned char rData[9]={0};
			unsigned char showData[17]={0};
			int st ;
			st =fw_config_card((HANDLE)icdev,'B');
			st =fw_request_b((HANDLE)icdev,0,0, 0,ATQB);
			if(st)
			{
				ShowMsgString(_T("Find card Error!"));
				return;
			}
			st =fw_attrib_ID((HANDLE)icdev,UIDinfo, &len);
			if(st)
			{
				ShowMsgString(_T("Read ID Number Error!"));
				return;
			}
			else
			{
				ShowMsgString(_T("Read ID Number OK!"));
				CString strResetInfo("ID Number: ");

				for(int i = 0 ; i < 8 ; i++)
					rData[i]=UIDinfo[i];
				hex_a(showData,rData,16);
				
				strResetInfo+=showData;
				ShowMsgString(strResetInfo);
			}

}
